import React, { useState, useEffect, useRef } from "react";
import Editor, { useMonaco, loader } from "@monaco-editor/react";
import { useNavigate } from "react-router-dom";
import {
    Select,
    Divider,
    Button,
    Input,
    InputNumber,
    Row,
    Col,
    message,
} from "antd";
// import JarTreeViewer from "./getEditorValue";
import { postLookFileContext } from "@/services/hosting/api";
import { useLocation } from "umi";
import { Avatar, List, Skeleton } from "antd";
import InfiniteScroll from "react-infinite-scroll-component";

interface DataType {
    gender?: string;
    name?: string;
    email?: string;
    avatar?: string;
    id?: string;
}

// 配置本地资源路径
loader.config({ paths: { vs: "/monaco-editor/vs" } });

const Histlog: React.FC = () => {
    const [defaultCode, setDefaultCode] = useState<string>(
        "// Write your code here",
    );
    const location = useLocation();
    const params = new URLSearchParams(location.search);
    const appId: string = params.get("appId") || "";
    const stype: string = params.get("type") || "";
    const [resetButton, setResetButtom] = useState(false);
    const [code, setCode] = useState<string>("");
    const [language, setLanguage] = useState<string>("plaintext");
    const monaco = useMonaco();
    const editorRef = useRef<any>(null);
    const [fontSize, setFontSize] = useState<number>(14);
    const [fileName, setFileName] = useState<string>("");

    const [sidebarWidth, setSidebarWidth] = useState(250);
    const isDraggingRef = useRef(false);
    const startXRef = useRef(0);
    const startWidthRef = useRef(0);

    const handleMouseDown = (e: React.MouseEvent) => {
        isDraggingRef.current = true;
        startXRef.current = e.clientX;
        startWidthRef.current = sidebarWidth;
        document.addEventListener("mousemove", handleMouseMove);
        document.addEventListener("mouseup", handleMouseUp);
    };

    const handleMouseMove = (e: MouseEvent) => {
        if (!isDraggingRef.current) return;
        const deltaX = e.clientX - startXRef.current;
        const newWidth = Math.max(
            200,
            Math.min(400, startWidthRef.current + deltaX),
        );
        setSidebarWidth(newWidth);
    };

    const handleMouseUp = () => {
        isDraggingRef.current = false;
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
    };
    const handleFontSizeWheel = (e: React.WheelEvent) => {
        const delta = e.deltaY > 0 ? -1 : 1;
        setFontSize(Math.max(1, Math.min(50, fontSize + delta)));
    };
    const navigate = useNavigate();
    // const codeContextGet = async (values: API.PostJarContext) => {
    //     try {
    //         const res = (await postJarContext(
    //             { ...values },
    //             navigate,
    //         )) as API.PostJarContextResult;
    //         if (typeof res.message === "string") {
    //             message.error(res.message);
    //             setCode("加载文件内容失败");
    //         } else if (Array.isArray(res.message)) {
    //             const firstItem = res.message[0];
    //             if (firstItem.value === null) {
    //                 message.info("二进制文件无法加载！");
    //                 setCode("无法查看二进制文件！");
    //             } else {
    //                 setDefaultCode(firstItem.value);
    //                 setCode(firstItem.value);
    //                 setLanguage(firstItem.guess);
    //             }
    //         } else {
    //             if (res.message.value === null) {
    //                 message.info("二进制文件无法加载！");
    //                 setCode("无法查看二进制文件！");
    //             } else {
    //                 setDefaultCode(res.message.value);
    //                 setCode(res.message.value);
    //                 setLanguage(res.message.guess);
    //             }
    //         }
    //     } catch (err) {
    //         console.error(err);
    //         message.error("加载文件内容失败");
    //     }
    // };
    useEffect(() => {
        return () => {
            document.removeEventListener("mousemove", handleMouseMove);
            document.removeEventListener("mouseup", handleMouseUp);
        };
    }, []);
    const handleFind = () => {
        if (editorRef.current) {
            editorRef.current.focus();
            editorRef.current.trigger("", "actions.find", {});
        }
    };
    const saveCode = () => {
        message.info("调取保存api");
        return true;
    };

    const resetCode = () => {
        setCode(defaultCode);
        setResetButtom(false);
    };
    const formatCode = () => {
        if (editorRef.current) {
            editorRef.current.getAction("editor.action.formatDocument").run();
        }
    };

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<DataType[]>([]);
    const [page, setPage] = useState(1);

    const loadMoreData = () => {
        if (loading) {
            return;
        }
        setLoading(true);
        fetch(
            `https://660d2bd96ddfa2943b33731c.mockapi.io/api/users/?page=${page}&limit=10`,
        )
            .then((res) => res.json())
            .then((res) => {
                const results = Array.isArray(res) ? res : [];
                setData([...data, ...results]);
                setLoading(false);
                setPage(page + 1);
            })
            .catch(() => {
                setLoading(false);
            });
    };

    useEffect(() => {
        loadMoreData();
    }, []);

    return (
        <div
            style={{
                height: "100%",
                display: "flex",
                flexDirection: "column",
                overflow: "hidden",
            }}
        >
            <div style={{ flex: 1, display: "flex", overflow: "hidden" }}>
                {/* 左侧文件树 - 现在宽度可调整 */}
                <div
                    style={{
                        width: sidebarWidth,
                        minWidth: 200, // 最小宽度
                        background: "#fff",
                        display: "flex",
                        flexDirection: "column",
                        overflow: "hidden",
                        position: "relative", // 为分界线定位
                    }}
                >
                    <div
                        style={{
                            padding: "10px",
                            fontSize: "20px",
                        }}
                    >
                        历史日志
                    </div>
                    <div
                        id="scrollableDiv"
                        style={{
                            height: "63vh",
                            overflow: "auto",
                        }}
                    >
                        <InfiniteScroll
                            dataLength={data.length}
                            next={loadMoreData}
                            hasMore={data.length < 50}
                            loader={
                                <Skeleton
                                    avatar
                                    paragraph={{ rows: 1 }}
                                    active
                                />
                            }
                            endMessage={<Divider plain>没有更多了...</Divider>}
                            scrollableTarget="scrollableDiv"
                        >
                            <List
                                dataSource={data}
                                renderItem={(item) => (
                                    <List.Item key={item.email}>内容</List.Item>
                                )}
                            />
                        </InfiniteScroll>
                    </div>
                </div>

                {/* 右侧编辑器 */}
                <div
                    style={{
                        flex: 1,
                        minWidth: 400, // 编辑器最小宽度
                        display: "flex",
                        flexDirection: "column",
                        overflow: "hidden",
                    }}
                >
                    {/* 右侧编辑器 */}
                    <div
                        style={{
                            flex: 1,
                            display: "flex",
                            flexDirection: "column",
                            overflow: "hidden",
                        }}
                    >
                        {/* 编辑器控制栏 */}
                        <div
                            style={{
                                padding: "10px 16px",
                                background: "#fff",
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                                // borderBottom: "1px solid #f0f0f0",
                                flexWrap: "wrap",
                                gap: 16,
                            }}
                        >
                            <div
                                style={{
                                    display: "flex",
                                    alignItems: "center",
                                    gap: 16,
                                }}
                            >
                                <div
                                    style={{
                                        display: "flex",
                                        alignItems: "center",
                                        gap: 8,
                                    }}
                                ></div>

                                <div
                                    style={{
                                        display: "flex",
                                        alignItems: "center",
                                        gap: 8,
                                    }}
                                >
                                    <span>字体大小：</span>
                                    <InputNumber
                                        min={1}
                                        max={50}
                                        value={fontSize}
                                        onWheel={handleFontSizeWheel}
                                        onChange={(newValue) =>
                                            setFontSize(newValue || 1)
                                        }
                                    />
                                </div>
                            </div>

                            <div
                                style={{
                                    display: "flex",
                                    alignItems: "center",
                                    gap: 8,
                                }}
                            >
                                <Button onClick={handleFind}>查找</Button>
                            </div>
                        </div>

                        {/* 编辑器主体 */}
                        <div style={{ height: "calc(100vh - 300px)" }}>
                            <Editor
                                height="100%"
                                language={language}
                                value={code}
                                onChange={(value) => {
                                    if (value !== defaultCode)
                                        setResetButtom(true);
                                    setCode(value || "");
                                }}
                                onMount={(editor) => {
                                    editorRef.current = editor;
                                }}
                                options={{
                                    readOnly: true,
                                    smoothScrolling: true,
                                    cursorSmoothCaretAnimation: "on",
                                    minimap: { enabled: true },
                                    fontSize: fontSize,
                                    wordWrap: "on",
                                    automaticLayout: true,
                                    scrollBeyondLastLine: false,
                                    renderWhitespace: "selection",
                                    tabSize: 4,
                                    formatOnPaste: true,
                                    formatOnType: true,
                                    quickSuggestions: true,
                                }}
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Histlog;
